import axios from 'axios'
import { Loading, Message } from 'element-ui'
import { CODE_STATE } from '@/api/code'
import router from '@/router'
import qs from 'qs'
axios.defaults.timeout = 60000
axios.defaults.withCredentials = false

let loading
let isShowLoading = true
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中....',
    background: 'rgba(0, 0, 0, 0.8)'
    // target: document.querySelector('.loading-area')// 设置加载动画区域
  })
}
function endLoading() {
  loading.close()
}

const pending = [] // 声明一个数组用于存储每个请求的取消函数和axios标识
var CancelToken = axios.CancelToken
const removePending = (config) => {
  for (const p in pending) {
    if (pending[p].u === config.url + '&' + config.method + '&' + config.data) { // 当当前请求在数组中存在时执行函数体
      pending[p].f() // 执行取消操作
      pending.splice(p, 1)
    }
  }
}

// 声明一个对象用于存储请求个数
let needLoadingRequestCount = 0
function showFullScreenLoading() {
  console.log('isShowLoading', isShowLoading)
  if (needLoadingRequestCount === 0 && isShowLoading) {
    startLoading()
  }
  needLoadingRequestCount++
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0 && isShowLoading) {
    endLoading()
  }
}

// 请求拦截
axios.interceptors.request.use(

  (config) => {
    // 设置请求头
    removePending(config) // 在一个axios发送前执行一下取消操作
    // const token = store.getters.accessToken
    const token = window.localStorage.getItem('token')

    const timestamp = Date.parse(new Date())
    if (token) {
      config.headers['token'] = token
    }
    config.headers['timestamp'] = timestamp
    config.headers['sign'] = 'hR5S8a3flTkTbncb'
    config.cancelToken = new CancelToken((c) => {
      // 这里的axios标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
      pending.push({ u: config.url + '&' + config.method, f: c })// config.data为请求参数
    })

    showFullScreenLoading()
    return config
  },
  (error) => {
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)
// 响应拦截
axios.interceptors.response.use(
  (res) => {
    tryHideFullScreenLoading()
    removePending(res.config) // 在一个axios响应后再执行一下取消操作，把已经完成的请求从pending中移除
    const code = res.data.status
    if (code === 401) {
      Message({
        message: res.data.message,
        showClose: true,
        type: 'warning',
        duration: 2000
      })
      // 清除token
      router.push('/login')
      localStorage.clear()
    }
    return res
  },
  (error) => {
    Message.error(error)
    tryHideFullScreenLoading()
    if (error.message === 'Network Error') {
      Message({
        message: '网络异常，请检查网络连接！',
        showClose: true,
        type: 'error',
        duration: 2000
      })
    } else {
      // 获取状态码
      const { status } = error.response

      if (status === 401) {
        Message.error('请重新登录')
        // 清除token
        localStorage.clear()
        // 跳转到登录页面
        router.push('/login')
      }
    }
    return Promise.reject(error)
  }
)

export function setShowLoading(val) {
  isShowLoading = val
}
export function Fecth(
  url,
  data,
  _method = 'POST',
  headers = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
) {
  if (_method === 'POST') {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: qs.stringify(data),
        headers: headers,
        method: _method
      })
        .then(response => {
          if (response.status === CODE_STATE.SUCCESS_OK) {
            resolve(response.data)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}
